/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package storymotion.photo;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import storymotion.config.Configuration;
import storymotion.keyword.Keyword;
import storymotion.keyword.KeywordDAO;
import storymotion.user.User;

/**
 *
 * @author leoomoreira
 */
public class PhotoUploadInsert extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        PhotoDAO photoDAO = null;
        KeywordDAO keywordDAO = null;
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                photoDAO = new PhotoDAO();
                keywordDAO = new KeywordDAO();
                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                long newId = -1;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField()) {
                        //String fieldName = item.getFieldName();
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        //long sizeInBytes = item.getSize();
                        try {
                            newId = photoDAO.getNewId();
                            Photo photo = new Photo();
                            photo.setId(newId);
                            photo.setName(fileName);
                            photo.setExtension(contentType);
                            photo.setDate(new Date());
                            photo.setUserId(user.getId());
                            item.write(new File(Configuration.PHOTOPATH + newId + "_" + fileName));
                            photoDAO.insert(photo);
                            photoDAO.commit();
                        } catch (Exception ex) {
                            throw new SQLException(ex);
                        }
                    } else {
                        String fieldName = item.getFieldName();
                        if (fieldName.equals("keywords") && newId > 0) {
                            String keywordsStr = item.getString();
                            if (keywordsStr != null && keywordsStr.trim().length() > 0) {
                                if (keywordsStr.contains(";")) {
                                    String[] keywords = keywordsStr.split(";");
                                    for (String k : keywords) {
                                        if (k != null) {
                                            Keyword keyword = new Keyword();
                                            keyword.setPhotoId(newId);
                                            keyword.setKeyword(k.trim());
                                            keywordDAO.insert(keyword);
                                        }
                                    }
                                } else {
                                    Keyword keyword = new Keyword();
                                    keyword.setPhotoId(newId);
                                    keyword.setKeyword(keywordsStr.trim());
                                    keywordDAO.insert(keyword);
                                }
                            }
                        }
                    }
                }
                photoDAO.commit();
                keywordDAO.commit();
                request.setAttribute("message", "Photo successfully registered");
                request.getRequestDispatcher("MainServlet").forward(request, response);
            } catch (FileUploadException ex) {
                request.setAttribute("message", ex.getMessage());
                try {
                    if (photoDAO != null) {
                        photoDAO.rollback();
                    }
                    if (keywordDAO != null) {
                        keywordDAO.rollback();
                    }
                } catch (SQLException ex1) {
                }
            } catch (SQLException ex) {
                request.setAttribute("message", ex.getMessage());
                try {
                    if (photoDAO != null) {
                        photoDAO.rollback();
                    }
                    if (keywordDAO != null) {
                        keywordDAO.rollback();
                    }
                } catch (SQLException ex1) {
                }
            }
        } else {
            request.setAttribute("message", "This form was not design to allow transfer of files");
            request.getRequestDispatcher("MainServlet").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
